<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/Frog_16px_1177822_easyicon.net.ico">
  <link rel="mask-icon" href="/images/Frog_32px_1177822_easyicon.net.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"hxy1997.xyz","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":true,"nav":null,"activeClass":"valine"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"输入关键字","hits_empty":"没有找到与「${query}」相关搜索","hits_stats":"${hits} 条相关记录，共耗时 ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="转自 https:&#x2F;&#x2F;juejin.im&#x2F;post&#x2F;6844904096525189128  笔者刚接触async&#x2F;await时，就被其暂停执行的特性吸引了，心想在没有原生API支持的情况下，await居然能挂起当前方法，实现暂停执行，我感到十分好奇。好奇心驱使我一层一层剥开有关JS异步编程的一切。阅读完本文，读者应该能够了解：  Promise的实现原理  async&#x2F;await的实现原理  G">
<meta property="og:type" content="article">
<meta property="og:title" content="Promise async Generator实现原理解析">
<meta property="og:url" content="https://hxy1997.xyz/2020/10/30/Promise%20async%20Generator%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86%E8%A7%A3%E6%9E%90/index.html">
<meta property="og:site_name" content="hxy的博客">
<meta property="og:description" content="转自 https:&#x2F;&#x2F;juejin.im&#x2F;post&#x2F;6844904096525189128  笔者刚接触async&#x2F;await时，就被其暂停执行的特性吸引了，心想在没有原生API支持的情况下，await居然能挂起当前方法，实现暂停执行，我感到十分好奇。好奇心驱使我一层一层剥开有关JS异步编程的一切。阅读完本文，读者应该能够了解：  Promise的实现原理  async&#x2F;await的实现原理  G">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210518223054.webp">
<meta property="article:published_time" content="2020-10-29T16:00:00.000Z">
<meta property="article:modified_time" content="2021-05-18T14:31:54.008Z">
<meta property="article:author" content="hxy">
<meta property="article:tag" content="Promise">
<meta property="article:tag" content="async">
<meta property="article:tag" content="Generator">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210518223054.webp">

<link rel="canonical" href="https://hxy1997.xyz/2020/10/30/Promise%20async%20Generator%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86%E8%A7%A3%E6%9E%90/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Promise async Generator实现原理解析 | hxy的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="hxy的博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">hxy的博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Mia san Mia!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/huxingyi1997" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://hxy1997.xyz/2020/10/30/Promise%20async%20Generator%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86%E8%A7%A3%E6%9E%90/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/Robben.gif">
      <meta itemprop="name" content="hxy">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="hxy的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Promise async Generator实现原理解析
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-10-30 00:00:00" itemprop="dateCreated datePublished" datetime="2020-10-30T00:00:00+08:00">2020-10-30</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-05-18 22:31:54" itemprop="dateModified" datetime="2021-05-18T22:31:54+08:00">2021-05-18</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/web%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">web前端</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="热度" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">热度：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2020/10/30/Promise%20async%20Generator%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86%E8%A7%A3%E6%9E%90/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2020/10/30/Promise%20async%20Generator%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86%E8%A7%A3%E6%9E%90/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>转自 <a target="_blank" rel="noopener" href="https://juejin.im/post/6844904096525189128">https://juejin.im/post/6844904096525189128</a> </p>
<p>笔者刚接触<code>async/await</code>时，就被其暂停执行的特性吸引了，心想在没有原生API支持的情况下，await居然能挂起当前方法，实现暂停执行，我感到十分好奇。好奇心驱使我一层一层剥开有关JS异步编程的一切。阅读完本文，读者应该能够了解：</p>
<ol>
<li><p><code>Promise</code>的实现原理</p>
</li>
<li><p><code>async/await</code>的实现原理</p>
</li>
<li><p><code>Generator</code>的实现原理</p>
</li>
</ol>
<span id="more"></span>

<h1 id="Promise实现"><a href="#Promise实现" class="headerlink" title="Promise实现"></a>Promise实现</h1><p>在成文过程中，笔者查阅了很多讲解Promise实现的文章，但感觉大多文章都很难称得上条理清晰，有的上来就放大段Promise规范翻译，有的在Promise基础使用上浪费篇幅，又或者把一个简单的东西长篇大论，过度讲解，我推荐头铁的同学直接拉到本章小结看最终实现，结合着注释直接啃代码也能理解十之八九</p>
<p>回归正题，文章开头我们先点一下Promise为我们解决了什么问题：在传统的异步编程中，如果异步之间存在依赖关系，我们就需要通过层层嵌套回调来满足这种依赖，如果嵌套层数过多，可读性和可维护性都变得很差，产生所谓“回调地狱”，而Promise将回调嵌套改为链式调用，增加可读性和可维护性。下面我们就来一步步实现一个Promise：</p>
<h2 id="1-观察者模式"><a href="#1-观察者模式" class="headerlink" title="1. 观察者模式"></a>1. 观察者模式</h2><p>我们先来看一个最简单的Promise使用：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 新建一个Promise实例</span></span><br><span class="line"><span class="keyword">const</span> p1 = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">	<span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">		resolve(<span class="string">&#x27;result&#x27;</span>);</span><br><span class="line">	&#125;, <span class="number">1000</span>);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 传入resolve, reject函数参数</span></span><br><span class="line">p1.then(<span class="function"><span class="params">res</span> =&gt;</span> <span class="built_in">console</span>.log(res), <span class="function"><span class="params">err</span> =&gt;</span> <span class="built_in">console</span>.log(err))</span><br></pre></td></tr></table></figure>

<p>观察这个例子，我们分析Promise的调用流程：</p>
<ul>
<li><code>Promise</code>的构造方法接收一个<code>executor()</code>，在<code>new Promise()</code>时就立刻执行这个executor回调</li>
<li><code>executor()</code>内部的异步任务被放入宏/微任务队列，等待执行</li>
<li><code>then()</code>被执行，收集成功/失败回调，放入成功/失败队列</li>
<li><code>executor()</code>的异步任务被执行，触发<code>resolve/reject</code>，从成功/失败队列中取出回调依次执行</li>
</ul>
<p>其实熟悉设计模式的同学，很容易就能意识到这是个<strong>观察者模式</strong>，这种<code>收集依赖 -&gt; 触发通知 -&gt; 取出依赖执行</code> 的方式，被广泛运用于观察者模式的实现，在Promise里，执行顺序是<code>then收集依赖 -&gt; 异步触发resolve -&gt; resolve执行依赖</code>。依此，我们可以勾勒出Promise的大致形状：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyPromise</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 构造方法接收一个回调</span></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">executor</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>._resolveQueue = []    <span class="comment">// then收集的执行成功的回调队列</span></span><br><span class="line">        <span class="built_in">this</span>._rejectQueue = []     <span class="comment">// then收集的执行失败的回调队列</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 由于resolve/reject是在executor内部被调用, 因此需要使用箭头函数固定this指向, 否则找不到this._resolveQueue</span></span><br><span class="line">        <span class="keyword">let</span> _resolve = <span class="function">(<span class="params">val</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">// 从成功队列里取出回调依次执行</span></span><br><span class="line">            <span class="keyword">while</span>(<span class="built_in">this</span>._resolveQueue.length) &#123;</span><br><span class="line">                <span class="keyword">const</span> callback = <span class="built_in">this</span>._resolveQueue.shift()</span><br><span class="line">                callback(val)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 实现同resolve</span></span><br><span class="line">        <span class="keyword">let</span> _reject = <span class="function">(<span class="params">val</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">while</span>(<span class="built_in">this</span>._rejectQueue.length) &#123;</span><br><span class="line">                <span class="keyword">const</span> callback = <span class="built_in">this</span>._rejectQueue.shift()</span><br><span class="line">                callback(val)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// new Promise()时立即执行executor,并传入resolve和reject</span></span><br><span class="line">        executor(_resolve, _reject)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// then方法,接收一个成功的回调和一个失败的回调，并push进对应队列</span></span><br><span class="line">    <span class="function"><span class="title">then</span>(<span class="params">resolveFn, rejectFn</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>._resolveQueue.push(resolveFn)</span><br><span class="line">        <span class="built_in">this</span>._rejectQueue.push(rejectFn)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>写完代码我们可以测试一下:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> p1 = <span class="keyword">new</span> MyPromise(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    	resolve(<span class="string">&#x27;result&#x27;</span>)</span><br><span class="line">    &#125;, <span class="number">1000</span>);</span><br><span class="line">&#125;)</span><br><span class="line">p1.then(<span class="function"><span class="params">res</span> =&gt;</span> <span class="built_in">console</span>.log(res))</span><br><span class="line"><span class="comment">// 一秒后输出result</span></span><br></pre></td></tr></table></figure>

<p>我们运用观察者模式简单的实现了一下<code>then</code>和<code>resolve</code>，使我们能够在then方法的回调里取得异步操作的返回值，但我们这个Promise离最终实现还有很长的距离，下面我们来一步步补充这个Promise：</p>
<h2 id="2-Promise-A-规范"><a href="#2-Promise-A-规范" class="headerlink" title="2. Promise A+规范"></a>2. Promise A+规范</h2><p>上面我们已经简单地实现了一个超低配版Promise，但我们会看到很多文章和我们写的不一样，他们的Promise实现中还引入了各种状态控制，这是由于ES6的Promise实现需要遵循<a target="_blank" rel="noopener" href="https://promisesaplus.com/">Promise/A+规范</a>，是规范对Promise的状态控制做了要求。Promise/A+的规范比较长，这里只总结两条核心规则：</p>
<blockquote>
<ol>
<li>Promise本质是一个状态机，且状态只能为以下三种：<code>Pending（等待态）</code>、<code>Fulfilled（执行态）</code>、<code>Rejected（拒绝态）</code>，状态的变更是单向的，只能从Pending -&gt; Fulfilled 或 Pending -&gt; Rejected，状态变更不可逆</li>
<li><code>then方法</code>接收两个可选参数，分别对应状态改变时触发的回调。then方法返回一个promise。then 方法可以被同一个 promise 调用多次。</li>
</ol>
</blockquote>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210518223054.webp" alt="img"></p>
<p>根据规范，我们补充一下Promise的代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//Promise/A+规范的三种状态</span></span><br><span class="line"><span class="keyword">const</span> PENDING = <span class="string">&#x27;pending&#x27;</span></span><br><span class="line"><span class="keyword">const</span> FULFILLED = <span class="string">&#x27;fulfilled&#x27;</span></span><br><span class="line"><span class="keyword">const</span> REJECTED = <span class="string">&#x27;rejected&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyPromise</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 构造方法接收一个回调</span></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">executor</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>._status = PENDING     <span class="comment">// Promise状态</span></span><br><span class="line">        <span class="built_in">this</span>._resolveQueue = []    <span class="comment">// 成功队列, resolve时触发</span></span><br><span class="line">        <span class="built_in">this</span>._rejectQueue = []     <span class="comment">// 失败队列, reject时触发</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 由于resolve/reject是在executor内部被调用, 因此需要使用箭头函数固定this指向, 否则找不到this._resolveQueue</span></span><br><span class="line">        <span class="keyword">let</span> _resolve = <span class="function">(<span class="params">val</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span>(<span class="built_in">this</span>._status !== PENDING) <span class="keyword">return</span>   <span class="comment">// 对应规范中的&quot;状态只能由pending到fulfilled或rejected&quot;</span></span><br><span class="line">            <span class="built_in">this</span>._status = FULFILLED              <span class="comment">// 变更状态</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 这里之所以使用一个队列来储存回调,是为了实现规范要求的 &quot;then 方法可以被同一个 promise 调用多次&quot;</span></span><br><span class="line">            <span class="comment">// 如果使用一个变量而非队列来储存回调,那么即使多次p1.then()也只会执行一次回调</span></span><br><span class="line">            <span class="keyword">while</span>(<span class="built_in">this</span>._resolveQueue.length) &#123;    </span><br><span class="line">                <span class="keyword">const</span> callback = <span class="built_in">this</span>._resolveQueue.shift()</span><br><span class="line">                callback(val)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 实现同resolve</span></span><br><span class="line">        <span class="keyword">let</span> _reject = <span class="function">(<span class="params">val</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span>(<span class="built_in">this</span>._status !== PENDING) <span class="keyword">return</span>   <span class="comment">// 对应规范中的&quot;状态只能由pending到fulfilled或rejected&quot;</span></span><br><span class="line">            <span class="built_in">this</span>._status = REJECTED               <span class="comment">// 变更状态</span></span><br><span class="line">            <span class="keyword">while</span>(<span class="built_in">this</span>._rejectQueue.length) &#123;</span><br><span class="line">                <span class="keyword">const</span> callback = <span class="built_in">this</span>._rejectQueue.shift()</span><br><span class="line">                callback(val)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// new Promise()时立即执行executor,并传入resolve和reject</span></span><br><span class="line">        executor(_resolve, _reject)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// then方法,接收一个成功的回调和一个失败的回调</span></span><br><span class="line">    <span class="function"><span class="title">then</span>(<span class="params">resolveFn, rejectFn</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>._resolveQueue.push(resolveFn)</span><br><span class="line">        <span class="built_in">this</span>._rejectQueue.push(rejectFn)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="3-then的链式调用"><a href="#3-then的链式调用" class="headerlink" title="3. then的链式调用"></a>3. then的链式调用</h2><p>补充完规范，我们接着来实现链式调用，这是Promise实现的重点和难点，我们先来看一下then是如何链式调用的：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">const p1 &#x3D; new Promise((resolve, reject) &#x3D;&gt; &#123;</span><br><span class="line">  	resolve(1)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">p1.then(res &#x3D;&gt; &#123;</span><br><span class="line">        console.log(res)</span><br><span class="line">        &#x2F;&#x2F;then回调中可以return一个Promise</span><br><span class="line">        return new Promise((resolve, reject) &#x3D;&gt; &#123;</span><br><span class="line">            setTimeout(() &#x3D;&gt; &#123;</span><br><span class="line">            	resolve(2)</span><br><span class="line">            &#125;, 1000)</span><br><span class="line">     	&#125;)</span><br><span class="line">     &#125;)</span><br><span class="line">    .then(res &#x3D;&gt; &#123;</span><br><span class="line">        console.log(res)</span><br><span class="line">        &#x2F;&#x2F;then回调中也可以return一个值</span><br><span class="line">        return 3</span><br><span class="line">    &#125;)</span><br><span class="line">    .then(res &#x3D;&gt; &#123;</span><br><span class="line">    	console.log(res)</span><br><span class="line">    &#125;)</span><br></pre></td></tr></table></figure>

<p>输出</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span></span><br><span class="line"><span class="number">2</span></span><br><span class="line"><span class="number">3</span></span><br></pre></td></tr></table></figure>

<p>我们思考一下如何实现这种链式调用：</p>
<ol>
<li>显然<code>.then()</code>需要返回一个Promise，这样才能找到then方法，所以我们会把then方法的返回值包装成Promise。</li>
<li><code>.then()</code>的回调需要拿到上一个<code>.then()</code>的返回值</li>
<li><code>.then()</code>的回调需要顺序执行，以上面这段代码为例，虽然中间return了一个Promise，但执行顺序仍要保证是1-&gt;2-&gt;3。我们要等待当前Promise状态变更后，再执行下一个then收集的回调，这就要求我们对then的返回值分类讨论</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// then方法改进</span></span><br><span class="line"><span class="function"><span class="title">then</span>(<span class="params">resolveFn, rejectFn</span>)</span> &#123;</span><br><span class="line">    <span class="comment">// return一个新的promise</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> MyPromise(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 把resolveFn重新包装一下,再push进resolve执行队列,这是为了能够获取回调的返回值进行分类讨论</span></span><br><span class="line">        <span class="keyword">const</span> fulfilledFn = <span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">//执行第一个(当前的)Promise的成功回调,并获取返回值</span></span><br><span class="line">                <span class="keyword">let</span> x = resolveFn(value)</span><br><span class="line">                <span class="comment">//分类讨论返回值,如果是Promise,那么等待Promise状态变更,否则直接resolve</span></span><br><span class="line">                <span class="comment">//这里resolve之后，就能被下一个.then()的回调获取到返回值，从而实现链式调用</span></span><br><span class="line">                x <span class="keyword">instanceof</span> MyPromise ? x.then(resolve, reject) : resolve(x)</span><br><span class="line">            &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">                reject(error)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//把后续then收集的依赖都push进当前Promise的成功回调队列中(_rejectQueue), 这是为了保证顺序调用</span></span><br><span class="line">        <span class="built_in">this</span>._resolveQueue.push(fulfilledFn)</span><br><span class="line"></span><br><span class="line">        <span class="comment">// reject同理</span></span><br><span class="line">        <span class="keyword">const</span> rejectedFn  = <span class="function"><span class="params">error</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">let</span> x = rejectFn(error)</span><br><span class="line">                x <span class="keyword">instanceof</span> MyPromise ? x.then(resolve, reject) : resolve(x)</span><br><span class="line">            &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">                reject(error)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">this</span>._rejectQueue.push(rejectedFn)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后我们就能测试一下链式调用：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> p1 = <span class="keyword">new</span> MyPromise(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        	resolve(<span class="number">1</span>)</span><br><span class="line">      &#125;, <span class="number">500</span>);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">p1</span><br><span class="line">    .then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(res)</span><br><span class="line">        <span class="keyword">return</span> <span class="number">2</span></span><br><span class="line">    &#125;)</span><br><span class="line">    .then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(res)</span><br><span class="line">        <span class="keyword">return</span> <span class="number">3</span></span><br><span class="line">    &#125;)</span><br><span class="line">    .then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">    	<span class="built_in">console</span>.log(res)</span><br><span class="line">    &#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 输出 1 2 3</span></span><br></pre></td></tr></table></figure>



<h2 id="4-值穿透-amp-状态已变更的情况"><a href="#4-值穿透-amp-状态已变更的情况" class="headerlink" title="4.值穿透 &amp; 状态已变更的情况"></a>4.值穿透 &amp; 状态已变更的情况</h2><p>我们已经初步完成了链式调用，但是对于 then() 方法，我们还要两个细节需要处理一下</p>
<ol>
<li><strong>值穿透</strong>：根据规范，如果 then() 接收的参数不是function，那么我们应该忽略它。如果没有忽略，当then()回调不为function时将会抛出异常，导致链式调用中断</li>
<li><strong>处理状态为resolve/reject的情况</strong>：其实我们上边 then() 的写法是对应状态为<code>padding</code>的情况，但是有些时候，resolve/reject 在 then() 之前就被执行（比如<code>Promise.resolve().then()</code>），如果这个时候还把then()回调push进resolve/reject的执行队列里，那么回调将不会被执行，因此对于状态已经变为<code>fulfilled</code>或<code>rejected</code>的情况，我们直接执行then回调：</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// then方法,接收一个成功的回调和一个失败的回调</span></span><br><span class="line"><span class="function"><span class="title">then</span>(<span class="params">resolveFn, rejectFn</span>)</span> &#123;</span><br><span class="line">    <span class="comment">// 根据规范，如果then的参数不是function，则我们需要忽略它, 让链式调用继续往下执行</span></span><br><span class="line">    <span class="keyword">typeof</span> resolveFn !== <span class="string">&#x27;function&#x27;</span> ? resolveFn = <span class="function"><span class="params">value</span> =&gt;</span> value : <span class="literal">null</span></span><br><span class="line">    <span class="keyword">typeof</span> rejectFn !== <span class="string">&#x27;function&#x27;</span> ? rejectFn = <span class="function"><span class="params">reason</span> =&gt;</span> &#123;</span><br><span class="line">    	<span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(reason <span class="keyword">instanceof</span> <span class="built_in">Error</span>? reason.message:reason);</span><br><span class="line">    &#125; : <span class="literal">null</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// return一个新的promise</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> MyPromise(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 把resolveFn重新包装一下,再push进resolve执行队列,这是为了能够获取回调的返回值进行分类讨论</span></span><br><span class="line">        <span class="keyword">const</span> fulfilledFn = <span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 执行第一个(当前的)Promise的成功回调,并获取返回值</span></span><br><span class="line">            <span class="keyword">let</span> x = resolveFn(value)</span><br><span class="line">            <span class="comment">// 分类讨论返回值,如果是Promise,那么等待Promise状态变更,否则直接resolve</span></span><br><span class="line">            x <span class="keyword">instanceof</span> MyPromise ? x.then(resolve, reject) : resolve(x)</span><br><span class="line">        &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">        	reject(error)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// reject同理</span></span><br><span class="line">    <span class="keyword">const</span> rejectedFn  = <span class="function"><span class="params">error</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">let</span> x = rejectFn(error)</span><br><span class="line">            x <span class="keyword">instanceof</span> MyPromise ? x.then(resolve, reject) : resolve(x)</span><br><span class="line">        &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">        	reject(error)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">switch</span> (<span class="built_in">this</span>._status) &#123;</span><br><span class="line">        <span class="comment">// 当状态为pending时,把then回调push进resolve/reject执行队列,等待执行</span></span><br><span class="line">        <span class="keyword">case</span> PENDING:</span><br><span class="line">            <span class="built_in">this</span>._resolveQueue.push(fulfilledFn)</span><br><span class="line">            <span class="built_in">this</span>._rejectQueue.push(rejectedFn)</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="comment">// 当状态已经变为resolve/reject时,直接执行then回调</span></span><br><span class="line">        <span class="keyword">case</span> FULFILLED:</span><br><span class="line">            fulfilledFn(<span class="built_in">this</span>._value)    <span class="comment">// this._value是上一个then回调return的值(见完整版代码)</span></span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> REJECTED:</span><br><span class="line">            rejectedFn(<span class="built_in">this</span>._value)</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="5-兼容同步任务"><a href="#5-兼容同步任务" class="headerlink" title="5.兼容同步任务"></a>5.兼容同步任务</h2><p>完成了then的链式调用以后，我们再处理一个前边的细节，然后放出完整代码。上文我们说过，Promise的执行顺序是<code>new Promise -&gt; then()收集回调 -&gt; resolve/reject执行回调</code>，这一顺序是建立在<strong>executor是异步任务</strong>的前提上的，如果executor是一个同步任务，那么顺序就会变成<code>new Promise -&gt; resolve/reject执行回调 -&gt; then()收集回调</code>，resolve的执行跑到then之前去了，为了兼容这种情况，我们给<code>resolve/reject</code>执行回调的操作包一个setTimeout，让它异步执行。</p>
<blockquote>
<p>这里插一句，有关这个setTimeout，其实还有一番学问。虽然规范没有要求回调应该被放进宏任务队列还是微任务队列，但其实Promise的默认实现是放进了微任务队列，我们的实现（包括大多数Promise手动实现和polyfill的转化）都是使用setTimeout放入了宏任务队列（当然我们也可以用MutationObserver模拟微任务）</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; Promise&#x2F;A+规定的三种状态</span><br><span class="line">const PENDING &#x3D; &#39;pending&#39;</span><br><span class="line">const FULFILLED &#x3D; &#39;fulfilled&#39;</span><br><span class="line">const REJECTED &#x3D; &#39;rejected&#39;</span><br><span class="line"></span><br><span class="line">class MyPromise &#123;</span><br><span class="line">  	&#x2F;&#x2F; 构造方法接收一个回调</span><br><span class="line">    constructor(executor) &#123;</span><br><span class="line">        this._status &#x3D; PENDING     &#x2F;&#x2F; Promise状态</span><br><span class="line">        this._value &#x3D; undefined    &#x2F;&#x2F; 储存then回调return的值</span><br><span class="line">        this._resolveQueue &#x3D; []    &#x2F;&#x2F; 成功队列, resolve时触发</span><br><span class="line">        this._rejectQueue &#x3D; []     &#x2F;&#x2F; 失败队列, reject时触发</span><br><span class="line"></span><br><span class="line">        &#x2F;&#x2F; 由于resolve&#x2F;reject是在executor内部被调用, 因此需要使用箭头函数固定this指向, 否则找不到this._resolveQueue</span><br><span class="line">        let _resolve &#x3D; (val) &#x3D;&gt; &#123;</span><br><span class="line">            &#x2F;&#x2F;把resolve执行回调的操作封装成一个函数,放进setTimeout里,以兼容executor是同步代码的情况</span><br><span class="line">            const run &#x3D; () &#x3D;&gt; &#123;</span><br><span class="line">                if(this._status !&#x3D;&#x3D; PENDING) return   &#x2F;&#x2F; 对应规范中的&quot;状态只能由pending到fulfilled或rejected&quot;</span><br><span class="line">                this._status &#x3D; FULFILLED              &#x2F;&#x2F; 变更状态</span><br><span class="line">                this._value &#x3D; val                     &#x2F;&#x2F; 储存当前value</span><br><span class="line"></span><br><span class="line">                &#x2F;&#x2F; 这里之所以使用一个队列来储存回调,是为了实现规范要求的 &quot;then 方法可以被同一个 promise 调用多次&quot;</span><br><span class="line">                &#x2F;&#x2F; 如果使用一个变量而非队列来储存回调,那么即使多次p1.then()也只会执行一次回调</span><br><span class="line">                while(this._resolveQueue.length) &#123;    </span><br><span class="line">                    const callback &#x3D; this._resolveQueue.shift()</span><br><span class="line">                    callback(val)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            setTimeout(run)</span><br><span class="line">        &#125;</span><br><span class="line">        &#x2F;&#x2F; 实现同resolve</span><br><span class="line">        let _reject &#x3D; (val) &#x3D;&gt; &#123;</span><br><span class="line">            const run &#x3D; () &#x3D;&gt; &#123;</span><br><span class="line">                if(this._status !&#x3D;&#x3D; PENDING) return   &#x2F;&#x2F; 对应规范中的&quot;状态只能由pending到fulfilled或rejected&quot;</span><br><span class="line">                this._status &#x3D; REJECTED               &#x2F;&#x2F; 变更状态</span><br><span class="line">                this._value &#x3D; val                     &#x2F;&#x2F; 储存当前value</span><br><span class="line">                while(this._rejectQueue.length) &#123;</span><br><span class="line">                    const callback &#x3D; this._rejectQueue.shift()</span><br><span class="line">                    callback(val)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            setTimeout(run)</span><br><span class="line">        &#125;</span><br><span class="line">        &#x2F;&#x2F; new Promise()时立即执行executor,并传入resolve和reject</span><br><span class="line">        executor(_resolve, _reject)</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">    &#x2F;&#x2F; then方法,接收一个成功的回调和一个失败的回调</span><br><span class="line">    then(resolveFn, rejectFn) &#123;</span><br><span class="line">        &#x2F;&#x2F; 根据规范，如果then的参数不是function，则我们需要忽略它, 让链式调用继续往下执行</span><br><span class="line">        typeof resolveFn !&#x3D;&#x3D; &#39;function&#39; ? resolveFn &#x3D; value &#x3D;&gt; value : null</span><br><span class="line">        typeof rejectFn !&#x3D;&#x3D; &#39;function&#39; ? rejectFn &#x3D; reason &#x3D;&gt; &#123;</span><br><span class="line">        	throw new Error(reason instanceof Error? reason.message:reason);</span><br><span class="line">        &#125; : null</span><br><span class="line"></span><br><span class="line">        &#x2F;&#x2F; return一个新的promise</span><br><span class="line">        return new MyPromise((resolve, reject) &#x3D;&gt; &#123;</span><br><span class="line">        &#x2F;&#x2F; 把resolveFn重新包装一下,再push进resolve执行队列,这是为了能够获取回调的返回值进行分类讨论</span><br><span class="line">        const fulfilledFn &#x3D; value &#x3D;&gt; &#123;</span><br><span class="line">            try &#123;</span><br><span class="line">                &#x2F;&#x2F; 执行第一个(当前的)Promise的成功回调,并获取返回值</span><br><span class="line">                let x &#x3D; resolveFn(value)</span><br><span class="line">                &#x2F;&#x2F; 分类讨论返回值,如果是Promise,那么等待Promise状态变更,否则直接resolve</span><br><span class="line">                x instanceof MyPromise ? x.then(resolve, reject) : resolve(x)</span><br><span class="line">            &#125; catch (error) &#123;</span><br><span class="line">            	reject(error)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">            &#x2F;&#x2F; reject同理</span><br><span class="line">            const rejectedFn  &#x3D; error &#x3D;&gt; &#123;</span><br><span class="line">                try &#123;</span><br><span class="line">                    let x &#x3D; rejectFn(error)</span><br><span class="line">                    x instanceof MyPromise ? x.then(resolve, reject) : resolve(x)</span><br><span class="line">                &#125; catch (error) &#123;</span><br><span class="line">                	reject(error)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            switch (this._status) &#123;</span><br><span class="line">                &#x2F;&#x2F; 当状态为pending时,把then回调push进resolve&#x2F;reject执行队列,等待执行</span><br><span class="line">                case PENDING:</span><br><span class="line">                    this._resolveQueue.push(fulfilledFn)</span><br><span class="line">                    this._rejectQueue.push(rejectedFn)</span><br><span class="line">                    break;</span><br><span class="line">                &#x2F;&#x2F; 当状态已经变为resolve&#x2F;reject时,直接执行then回调</span><br><span class="line">                case FULFILLED:</span><br><span class="line">                    fulfilledFn(this._value)    &#x2F;&#x2F; this._value是上一个then回调return的值(见完整版代码)</span><br><span class="line">                    break;</span><br><span class="line">                case REJECTED:</span><br><span class="line">                    rejectedFn(this._value)</span><br><span class="line">                    break;</span><br><span class="line">        	&#125;</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后我们可以测试一下这个Promise：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> p1 = <span class="keyword">new</span> MyPromise(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    resolve(<span class="number">1</span>)          <span class="comment">//同步executor测试</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">p1</span><br><span class="line">    .then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(res)</span><br><span class="line">        <span class="keyword">return</span> <span class="number">2</span>          <span class="comment">//链式调用测试</span></span><br><span class="line">    &#125;)</span><br><span class="line">    .then()             <span class="comment">//值穿透测试</span></span><br><span class="line">    .then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(res)</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> MyPromise(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">            resolve(<span class="number">3</span>)      <span class="comment">//返回Promise测试</span></span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">    .then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(res)</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&#x27;reject测试&#x27;</span>)   <span class="comment">//reject测试</span></span><br><span class="line">    &#125;)</span><br><span class="line">    .then(<span class="function">() =&gt;</span> &#123;&#125;, <span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(err)</span><br><span class="line">    &#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 输出 </span></span><br><span class="line"><span class="comment">// 1 </span></span><br><span class="line"><span class="comment">// 2 </span></span><br><span class="line"><span class="comment">// 3 </span></span><br><span class="line"><span class="comment">// Error: reject测试</span></span><br></pre></td></tr></table></figure>

<p>到这里，我们已经实现了Promise的主要功能<code>(｀∀´)Ψ</code>剩下的几个方法都非常简单，我们顺手收拾掉：</p>
<h2 id="Promise-prototype-catch"><a href="#Promise-prototype-catch" class="headerlink" title="Promise.prototype.catch()"></a>Promise.prototype.catch()</h2><blockquote>
<p><code>catch()方法</code>返回一个Promise，并且处理拒绝的情况。它的行为与调用Promise.prototype.then(undefined, onRejected) 相同。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// catch方法其实就是执行一下then的第二个回调</span></span><br><span class="line"><span class="keyword">catch</span>(rejectFn) &#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="built_in">this</span>.then(<span class="literal">undefined</span>, rejectFn)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="Promise-prototype-finally"><a href="#Promise-prototype-finally" class="headerlink" title="Promise.prototype.finally()"></a>Promise.prototype.finally()</h2><blockquote>
<p><code>finally()方法</code>返回一个Promise。在promise结束时，无论结果是fulfilled或者是rejected，都会执行指定的回调函数。在finally之后，还可以继续then。并且会将值原封不动的传递给后面的then</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; finally方法</span><br><span class="line">finally(callback) &#123;</span><br><span class="line">    return this.then(</span><br><span class="line">        value &#x3D;&gt; MyPromise.resolve(callback()).then(() &#x3D;&gt; value),             &#x2F;&#x2F; MyPromise.resolve执行回调,并在then中return结果传递给后面的Promise</span><br><span class="line">        reason &#x3D;&gt; MyPromise.resolve(callback()).then(() &#x3D;&gt; &#123; throw reason &#125;)  &#x2F;&#x2F; reject同理</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>PS. 有同学问我<code>MyPromise.resolve(callback())</code>的意义，这里补充解释一下：这个写法其实涉及到一个<code>finally()</code>的使用细节，<strong>finally()如果return了一个reject状态的Promise，将会改变当前Promise的状态</strong>，这个<code>MyPromise.resolve</code>就用于改变Promise状态，在finally()没有返回reject态Promise或throw错误的情况下，去掉<code>MyPromise.resolve</code>也是一样的（欢迎大家向我提问，勘误的过程中也能很好地加深自己对Promise的理解，大家可以在各个交流群里直接@我）</p>
<blockquote>
<p>参考资料：<a target="_blank" rel="noopener" href="https://www.jianshu.com/p/f0b94daf9bf7">对 Promise.prototype.finally() 的粗浅理解</a></p>
</blockquote>
<h2 id="Promise-resolve"><a href="#Promise-resolve" class="headerlink" title="Promise.resolve()"></a>Promise.resolve()</h2><blockquote>
<p><code>Promise.resolve(value)</code>方法返回一个以给定值解析后的Promise 对象。如果该值为promise，返回这个promise；如果这个值是thenable（即带有”then” 方法)），返回的promise会“跟随”这个thenable的对象，采用它的最终状态；否则返回的promise将以此值完成。此函数将类promise对象的多层嵌套展平。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 静态的resolve方法</span></span><br><span class="line"><span class="keyword">static</span> <span class="function"><span class="title">resolve</span>(<span class="params">value</span>)</span> &#123;</span><br><span class="line">    <span class="comment">// 根据规范, 如果参数是Promise实例, 直接return这个实例</span></span><br><span class="line">    <span class="keyword">if</span>(value <span class="keyword">instanceof</span> MyPromise) <span class="keyword">return</span> value </span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> MyPromise(<span class="function"><span class="params">resolve</span> =&gt;</span> resolve(value))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="Promise-reject"><a href="#Promise-reject" class="headerlink" title="Promise.reject()"></a>Promise.reject()</h2><blockquote>
<p><code>Promise.reject()</code>方法返回一个带有拒绝原因的Promise对象。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 静态的reject方法</span></span><br><span class="line"><span class="keyword">static</span> <span class="function"><span class="title">reject</span>(<span class="params">reason</span>)</span> &#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">new</span> MyPromise(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> reject(reason))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="Promise-all"><a href="#Promise-all" class="headerlink" title="Promise.all()"></a>Promise.all()</h2><blockquote>
<p><code>Promise.all(iterable)</code>方法返回一个 Promise 实例，此实例在 iterable 参数内所有的 promise 都“完成（resolved）”或参数中不包含 promise 时回调完成（resolve）；如果参数中  promise 有一个失败（rejected），此实例回调失败（reject），失败原因的是第一个失败 promise 的结果。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 静态的all方法</span></span><br><span class="line"><span class="keyword">static</span> <span class="function"><span class="title">all</span>(<span class="params">promiseArr</span>)</span> &#123;</span><br><span class="line">    <span class="keyword">let</span> index = <span class="number">0</span></span><br><span class="line">    <span class="keyword">let</span> result = []</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> MyPromise(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        promiseArr.forEach(<span class="function">(<span class="params">p, i</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">// Promise.resolve(p)用于处理传入值不为Promise的情况</span></span><br><span class="line">            MyPromise.resolve(p).then(</span><br><span class="line">                val =&gt; &#123;</span><br><span class="line">                    index++</span><br><span class="line">                    result[i] = val</span><br><span class="line">                    <span class="comment">// 所有then执行后, resolve结果</span></span><br><span class="line">                    <span class="keyword">if</span>(index === promiseArr.length) &#123;</span><br><span class="line">                        resolve(result)</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;,</span><br><span class="line">                err =&gt; &#123;</span><br><span class="line">                    <span class="comment">// 有一个Promise被reject时，MyPromise的状态变为reject</span></span><br><span class="line">                    reject(err)</span><br><span class="line">                &#125;</span><br><span class="line">            )</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="Promise-race"><a href="#Promise-race" class="headerlink" title="Promise.race()"></a>Promise.race()</h2><blockquote>
<p><code>Promise.race(iterable)</code>方法返回一个 promise，一旦迭代器中的某个promise解决或拒绝，返回的 promise就会解决或拒绝。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="function"><span class="title">race</span>(<span class="params">promiseArr</span>)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> MyPromise(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 同时执行Promise,如果有一个Promise的状态发生改变,就变更新MyPromise的状态</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">let</span> p <span class="keyword">of</span> promiseArr) &#123;</span><br><span class="line">            <span class="comment">// Promise.resolve(p)用于处理传入值不为Promise的情况</span></span><br><span class="line">            MyPromise.resolve(p).then(</span><br><span class="line">                value =&gt; &#123;</span><br><span class="line">                    <span class="comment">// 注意这个resolve是上边new MyPromise的</span></span><br><span class="line">                    resolve(value)</span><br><span class="line">                &#125;,</span><br><span class="line">                err =&gt; &#123;</span><br><span class="line">                    reject(err)</span><br><span class="line">                &#125;</span><br><span class="line">            )</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="完整代码"><a href="#完整代码" class="headerlink" title="完整代码"></a>完整代码</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Promise/A+规定的三种状态</span></span><br><span class="line"><span class="keyword">const</span> PENDING = <span class="string">&#x27;pending&#x27;</span></span><br><span class="line"><span class="keyword">const</span> FULFILLED = <span class="string">&#x27;fulfilled&#x27;</span></span><br><span class="line"><span class="keyword">const</span> REJECTED = <span class="string">&#x27;rejected&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyPromise</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 构造方法接收一个回调</span></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">executor</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>._status = PENDING     <span class="comment">// Promise状态</span></span><br><span class="line">        <span class="built_in">this</span>._value = <span class="literal">undefined</span>    <span class="comment">// 储存then回调return的值</span></span><br><span class="line">        <span class="built_in">this</span>._resolveQueue = []    <span class="comment">// 成功队列, resolve时触发</span></span><br><span class="line">        <span class="built_in">this</span>._rejectQueue = []     <span class="comment">// 失败队列, reject时触发</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 由于resolve/reject是在executor内部被调用, 因此需要使用箭头函数固定this指向, 否则找不到this._resolveQueue</span></span><br><span class="line">        <span class="keyword">let</span> _resolve = <span class="function">(<span class="params">val</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">//把resolve执行回调的操作封装成一个函数,放进setTimeout里,以兼容executor是同步代码的情况</span></span><br><span class="line">            <span class="keyword">const</span> run = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">                <span class="keyword">if</span> (<span class="built_in">this</span>._status !== PENDING) <span class="keyword">return</span>   <span class="comment">// 对应规范中的&quot;状态只能由pending到fulfilled或rejected&quot;</span></span><br><span class="line">                <span class="built_in">this</span>._status = FULFILLED              <span class="comment">// 变更状态</span></span><br><span class="line">                <span class="built_in">this</span>._value = val                     <span class="comment">// 储存当前value</span></span><br><span class="line"></span><br><span class="line">                <span class="comment">// 这里之所以使用一个队列来储存回调,是为了实现规范要求的 &quot;then 方法可以被同一个 promise 调用多次&quot;</span></span><br><span class="line">                <span class="comment">// 如果使用一个变量而非队列来储存回调,那么即使多次p1.then()也只会执行一次回调</span></span><br><span class="line">                <span class="keyword">while</span> (<span class="built_in">this</span>._resolveQueue.length) &#123;</span><br><span class="line">                    <span class="keyword">const</span> callback = <span class="built_in">this</span>._resolveQueue.shift()</span><br><span class="line">                    callback(val)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">setTimeout</span>(run)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 实现同resolve</span></span><br><span class="line">        <span class="keyword">let</span> _reject = <span class="function">(<span class="params">val</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">const</span> run = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">                <span class="keyword">if</span> (<span class="built_in">this</span>._status !== PENDING) <span class="keyword">return</span>   <span class="comment">// 对应规范中的&quot;状态只能由pending到fulfilled或rejected&quot;</span></span><br><span class="line">                <span class="built_in">this</span>._status = REJECTED               <span class="comment">// 变更状态</span></span><br><span class="line">                <span class="built_in">this</span>._value = val                     <span class="comment">// 储存当前value</span></span><br><span class="line">                <span class="keyword">while</span> (<span class="built_in">this</span>._rejectQueue.length) &#123;</span><br><span class="line">                    <span class="keyword">const</span> callback = <span class="built_in">this</span>._rejectQueue.shift()</span><br><span class="line">                    callback(val)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">setTimeout</span>(run)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// new Promise()时立即执行executor,并传入resolve和reject</span></span><br><span class="line">        executor(_resolve, _reject)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// then方法,接收一个成功的回调和一个失败的回调</span></span><br><span class="line">    <span class="function"><span class="title">then</span>(<span class="params">resolveFn, rejectFn</span>)</span> &#123;</span><br><span class="line">        <span class="comment">// 根据规范，如果then的参数不是function，则我们需要忽略它, 让链式调用继续往下执行</span></span><br><span class="line">        <span class="keyword">typeof</span> resolveFn !== <span class="string">&#x27;function&#x27;</span> ? resolveFn = <span class="function"><span class="params">value</span> =&gt;</span> value : <span class="literal">null</span></span><br><span class="line">        <span class="keyword">typeof</span> rejectFn !== <span class="string">&#x27;function&#x27;</span> ? rejectFn = <span class="function"><span class="params">reason</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(reason <span class="keyword">instanceof</span> <span class="built_in">Error</span> ? reason.message : reason);</span><br><span class="line">        &#125; : <span class="literal">null</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// return一个新的promise</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> MyPromise(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">// 把resolveFn重新包装一下,再push进resolve执行队列,这是为了能够获取回调的返回值进行分类讨论</span></span><br><span class="line">            <span class="keyword">const</span> fulfilledFn = <span class="function"><span class="params">value</span> =&gt;</span> &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    <span class="comment">// 执行第一个(当前的)Promise的成功回调,并获取返回值</span></span><br><span class="line">                    <span class="keyword">let</span> x = resolveFn(value)</span><br><span class="line">                    <span class="comment">// 分类讨论返回值,如果是Promise,那么等待Promise状态变更,否则直接resolve</span></span><br><span class="line">                    x <span class="keyword">instanceof</span> MyPromise ? x.then(resolve, reject) : resolve(x)</span><br><span class="line">                &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">                    reject(error)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// reject同理</span></span><br><span class="line">            <span class="keyword">const</span> rejectedFn = <span class="function"><span class="params">error</span> =&gt;</span> &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    <span class="keyword">let</span> x = rejectFn(error)</span><br><span class="line">                    x <span class="keyword">instanceof</span> MyPromise ? x.then(resolve, reject) : resolve(x)</span><br><span class="line">                &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">                    reject(error)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">switch</span> (<span class="built_in">this</span>._status) &#123;</span><br><span class="line">                <span class="comment">// 当状态为pending时,把then回调push进resolve/reject执行队列,等待执行</span></span><br><span class="line">                <span class="keyword">case</span> PENDING:</span><br><span class="line">                    <span class="built_in">this</span>._resolveQueue.push(fulfilledFn)</span><br><span class="line">                    <span class="built_in">this</span>._rejectQueue.push(rejectedFn)</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                <span class="comment">// 当状态已经变为resolve/reject时,直接执行then回调</span></span><br><span class="line">                <span class="keyword">case</span> FULFILLED:</span><br><span class="line">                    fulfilledFn(<span class="built_in">this</span>._value)    <span class="comment">// this._value是上一个then回调return的值(见完整版代码)</span></span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                <span class="keyword">case</span> REJECTED:</span><br><span class="line">                    rejectedFn(<span class="built_in">this</span>._value)</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//catch方法其实就是执行一下then的第二个回调</span></span><br><span class="line">    <span class="keyword">catch</span>(rejectFn) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.then(<span class="literal">undefined</span>, rejectFn)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//finally方法</span></span><br><span class="line">    <span class="function"><span class="title">finally</span>(<span class="params">callback</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.then(</span><br><span class="line">            value =&gt; MyPromise.resolve(callback()).then(<span class="function">() =&gt;</span> value),             <span class="comment">//执行回调,并returnvalue传递给后面的then</span></span><br><span class="line">            reason =&gt; MyPromise.resolve(callback()).then(<span class="function">() =&gt;</span> &#123; <span class="keyword">throw</span> reason &#125;)  <span class="comment">//reject同理</span></span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//静态的resolve方法</span></span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="title">resolve</span>(<span class="params">value</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (value <span class="keyword">instanceof</span> MyPromise) <span class="keyword">return</span> value <span class="comment">//根据规范, 如果参数是Promise实例, 直接return这个实例</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> MyPromise(<span class="function"><span class="params">resolve</span> =&gt;</span> resolve(value))</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//静态的reject方法</span></span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="title">reject</span>(<span class="params">reason</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> MyPromise(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> reject(reason))</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//静态的all方法</span></span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="title">all</span>(<span class="params">promiseArr</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> index = <span class="number">0</span></span><br><span class="line">        <span class="keyword">let</span> result = []</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> MyPromise(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">            promiseArr.forEach(<span class="function">(<span class="params">p, i</span>) =&gt;</span> &#123;</span><br><span class="line">                <span class="comment">//Promise.resolve(p)用于处理传入值不为Promise的情况</span></span><br><span class="line">                MyPromise.resolve(p).then(</span><br><span class="line">                    val =&gt; &#123;</span><br><span class="line">                        index++</span><br><span class="line">                        result[i] = val</span><br><span class="line">                        <span class="keyword">if</span> (index === promiseArr.length) &#123;</span><br><span class="line">                            resolve(result)</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;,</span><br><span class="line">                    err =&gt; &#123;</span><br><span class="line">                        reject(err)</span><br><span class="line">                    &#125;</span><br><span class="line">                )</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//静态的race方法</span></span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="title">race</span>(<span class="params">promiseArr</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> MyPromise(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">//同时执行Promise,如果有一个Promise的状态发生改变,就变更新MyPromise的状态</span></span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">let</span> p <span class="keyword">of</span> promiseArr) &#123;</span><br><span class="line">                MyPromise.resolve(p).then(  <span class="comment">//Promise.resolve(p)用于处理传入值不为Promise的情况</span></span><br><span class="line">                    value =&gt; &#123;</span><br><span class="line">                        resolve(value)        <span class="comment">//注意这个resolve是上边new MyPromise的</span></span><br><span class="line">                    &#125;,</span><br><span class="line">                    err =&gt; &#123;</span><br><span class="line">                        reject(err)</span><br><span class="line">                    &#125;</span><br><span class="line">                )</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>洋洋洒洒150多行的代码，到这里，我们终于可以给Promise的实现做一个结尾了。我们从一个最简单的Promise使用实例开始，通过对调用流程的分析，根据观察者模式实现了Promise的大致骨架，然后依据Promise/A+规范填充代码，重点实现了then 的链式调用，最后完成了Promise的静态/实例方法。其实Promise实现在整体上并没有太复杂的思想，但我们日常使用的时候往往忽略了很多Promise细节，因而很难写出一个符合规范的Promise实现，源码的实现过程，其实也是对Promise使用细节重新学习的过程。</p>
<h1 id="async-await实现"><a href="#async-await实现" class="headerlink" title="async/await实现"></a>async/await实现</h1><p>虽然前边花了这么多篇幅讲Promise的实现，不过探索<code>async/await</code>暂停执行的机制才是我们的初衷，下面我们就来进入这一块的内容。同样地，开头我们点一下async/await的使用意义。 在多个回调依赖的场景中，尽管Promise通过链式调用取代了回调嵌套，但过多的链式调用可读性仍然不佳，流程控制也不方便，ES7 提出的async 函数，终于让 JS 对于异步操作有了终极解决方案，简洁优美地解决了以上两个问题。</p>
<blockquote>
<p>设想一个这样的场景，异步任务a-&gt;b-&gt;c之间存在依赖关系，如果我们通过then链式调用来处理这些关系，可读性并不是很好，如果我们想控制其中某个过程，比如在某些条件下，b不往下执行到c，那么也不是很方便控制</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Promise</span>.resolve(a)</span><br><span class="line">    .then(<span class="function"><span class="params">b</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// do something</span></span><br><span class="line">    &#125;)</span><br><span class="line">    .then(<span class="function"><span class="params">c</span> =&gt;</span> &#123;</span><br><span class="line">    	<span class="comment">// do something</span></span><br><span class="line">    &#125;)</span><br></pre></td></tr></table></figure>

<blockquote>
<p>但是如果通过async/await来实现这个场景，可读性和流程控制都会方便不少。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">    <span class="keyword">const</span> a = <span class="keyword">await</span> <span class="built_in">Promise</span>.resolve(a);</span><br><span class="line">    <span class="keyword">const</span> b = <span class="keyword">await</span> <span class="built_in">Promise</span>.resolve(b);</span><br><span class="line">    <span class="keyword">const</span> c = <span class="keyword">await</span> <span class="built_in">Promise</span>.resolve(c);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>那么我们要如何实现一个async/await呢，首先我们要知道，<strong>async/await实际上是对Generator（生成器）的封装</strong>，是一个语法糖。由于Generator出现不久就被async/await取代了，很多同学对Generator比较陌生，因此我们先来看看Generator的用法：</p>
<blockquote>
<p>ES6 新引入了 Generator 函数，可以通过 yield 关键字，把函数的执行流挂起，通过next()方法可以切换到下一个状态，为改变执行流程提供了可能，从而为异步编程提供解决方案。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span>* <span class="title">myGenerator</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;1&#x27;</span></span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;2&#x27;</span></span><br><span class="line">    <span class="keyword">return</span> <span class="string">&#x27;3&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> gen = myGenerator();  <span class="comment">// 获取迭代器</span></span><br><span class="line">gen.next()  <span class="comment">// &#123;value: &quot;1&quot;, done: false&#125;</span></span><br><span class="line">gen.next()  <span class="comment">// &#123;value: &quot;2&quot;, done: false&#125;</span></span><br><span class="line">gen.next()  <span class="comment">// &#123;value: &quot;3&quot;, done: true&#125;</span></span><br></pre></td></tr></table></figure>

<p>也可以通过给<code>next()</code>传参, 让yield具有返回值</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span>* <span class="title">myGenerator</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">yield</span> <span class="string">&#x27;1&#x27;</span>)  <span class="comment">// 输出test1</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">yield</span> <span class="string">&#x27;2&#x27;</span>)  <span class="comment">// 输出test2</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">yield</span> <span class="string">&#x27;3&#x27;</span>)  <span class="comment">// 输出test3</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 获取迭代器</span></span><br><span class="line"><span class="keyword">const</span> gen = myGenerator();</span><br><span class="line"></span><br><span class="line">gen.next()</span><br><span class="line">gen.next(<span class="string">&#x27;test1&#x27;</span>)</span><br><span class="line">gen.next(<span class="string">&#x27;test2&#x27;</span>)</span><br><span class="line">gen.next(<span class="string">&#x27;test3&#x27;</span>)</span><br></pre></td></tr></table></figure>

<p>我们看到Generator的用法，应该️会感到很熟悉，<code>*/yield</code>和<code>async/await</code>看起来其实已经很相似了，它们都提供了暂停执行的功能，但二者又有三点不同：</p>
<ul>
<li><code>async/await</code>自带执行器，不需要手动调用next()就能自动执行下一步</li>
<li><code>async</code>函数返回值是Promise对象，而Generator返回的是生成器对象</li>
<li><code>await</code>能够返回Promise的resolve/reject的值</li>
</ul>
<p><strong>我们对async/await的实现，其实也就是对应以上三点封装Generator</strong></p>
<h2 id="1-自动执行"><a href="#1-自动执行" class="headerlink" title="1.自动执行"></a>1.自动执行</h2><p>我们先来看一下，对于这样一个Generator，手动执行是怎样一个流程</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span>* <span class="title">myGenerator</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">yield</span> <span class="built_in">Promise</span>.resolve(<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">yield</span> <span class="built_in">Promise</span>.resolve(<span class="number">2</span>);</span><br><span class="line">    <span class="keyword">yield</span> <span class="built_in">Promise</span>.resolve(<span class="number">3</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 手动执行迭代器</span></span><br><span class="line"><span class="keyword">const</span> gen = myGenerator()</span><br><span class="line">gen.next().value.then(<span class="function"><span class="params">val</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(val)</span><br><span class="line">    gen.next().value.then(<span class="function"><span class="params">val</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(val)</span><br><span class="line">        gen.next().value.then(<span class="function"><span class="params">val</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(val)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 输出1 2 3</span></span><br></pre></td></tr></table></figure>

<p>我们也可以通过给<code>gen.next()</code>传值的方式，让yield能返回resolve的值</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span>* <span class="title">myGenerator</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">yield</span> <span class="built_in">Promise</span>.resolve(<span class="number">1</span>))   <span class="comment">// 1</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">yield</span> <span class="built_in">Promise</span>.resolve(<span class="number">2</span>))   <span class="comment">// 2</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">yield</span> <span class="built_in">Promise</span>.resolve(<span class="number">3</span>))   <span class="comment">// 3</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 手动执行迭代器</span></span><br><span class="line"><span class="keyword">const</span> gen = myGenerator()</span><br><span class="line">gen.next().value.then(<span class="function"><span class="params">val</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// console.log(val)</span></span><br><span class="line">    gen.next(val).value.then(<span class="function"><span class="params">val</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// console.log(val)</span></span><br><span class="line">        gen.next(val).value.then(<span class="function"><span class="params">val</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">// console.log(val)</span></span><br><span class="line">            gen.next(val)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>显然，手动执行的写法看起来既笨拙又丑陋，我们希望生成器函数能自动往下执行，且yield能返回resolve的值，基于这两个需求，我们进行一个基本的封装，这里<code>async/await</code>是关键字，不能重写，我们用函数来模拟：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">run</span>(<span class="params">gen</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> g = gen()                     <span class="comment">// 由于每次gen()获取到的都是最新的迭代器,因此获取迭代器操作要放在_next()之前,否则会进入死循环</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">_next</span>(<span class="params">val</span>) </span>&#123;             <span class="comment">// 封装一个方法, 递归执行g.next()</span></span><br><span class="line">        <span class="keyword">var</span> res = g.next(val)           <span class="comment">// 获取迭代器对象，并返回resolve的值</span></span><br><span class="line">        <span class="keyword">if</span>(res.done) <span class="keyword">return</span> res.value   <span class="comment">// 递归终止条件</span></span><br><span class="line">            res.value.then(<span class="function"><span class="params">val</span> =&gt;</span> &#123;         <span class="comment">// Promise的then方法是实现自动迭代的前提</span></span><br><span class="line">            _next(val)                    <span class="comment">// 等待Promise完成就自动执行下一个next，并传入resolve的值</span></span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    _next()  <span class="comment">//第一次执行</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对于我们之前的例子，我们就能这样执行：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span>* <span class="title">myGenerator</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">yield</span> <span class="built_in">Promise</span>.resolve(<span class="number">1</span>))   <span class="comment">// 1</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">yield</span> <span class="built_in">Promise</span>.resolve(<span class="number">2</span>))   <span class="comment">// 2</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">yield</span> <span class="built_in">Promise</span>.resolve(<span class="number">3</span>))   <span class="comment">// 3</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">run(myGenerator)</span><br></pre></td></tr></table></figure>

<p>这样我们就初步实现了一个<code>async/await</code>。上边的代码只有五六行，但并不是一下就能看明白的，我们之前用了四个例子来做铺垫，也是为了让读者更好地理解这段代码。 简单来说，我们封装了一个run方法，run方法里我们把执行下一步的操作封装成<code>_next()</code>，每次Promise.then()的时候都去执行<code>_next()</code>，实现自动迭代的效果。在迭代的过程中，我们还把resolve的值传入<code>gen.next()</code>，使得yield得以返回Promise的resolve的值</p>
<blockquote>
<p>这里插一句，是不是只有<code>.then方法</code>这样的形式才能完成我们自动执行的功能呢？答案是否定的，yield后边除了接Promise，还可以接<code>thunk函数</code>，thunk函数不是一个新东西，所谓thunk函数，就是<strong>单参的只接受回调的函数</strong>，详细介绍可以看<a target="_blank" rel="noopener" href="https://user-gold-cdn.xitu.io/2020/3/15/170dc5e88df6c208">阮一峰Thunk 函数的含义和用法</a>，无论是Promise还是thunk函数，其核心都是通过<strong>传入回调</strong>的方式来实现Generator的自动执行。thunk函数只作为一个拓展知识，理解有困难的同学也可以跳过这里，并不影响后续理解。</p>
</blockquote>
<h2 id="2-返回Promise-amp-异常处理"><a href="#2-返回Promise-amp-异常处理" class="headerlink" title="2.返回Promise &amp; 异常处理"></a>2.返回Promise &amp; 异常处理</h2><p>虽然我们实现了Generator的自动执行以及让yield返回resolve的值，但上边的代码还存在着几点问题：</p>
<ol>
<li><strong>需要兼容基本类型</strong>：这段代码能自动执行的前提是<code>yield</code>后面跟Promise，为了兼容后面跟着基本类型值的情况，我们需要把yield跟的内容(<code>gen().next.value</code>)都用<code>Promise.resolve()</code>转化一遍</li>
<li><strong>缺少错误处理</strong>：上边代码里的Promise如果执行失败，就会导致后续执行直接中断，我们需要通过调用<code>Generator.prototype.throw()</code>，把错误抛出来，才能被外层的try-catch捕获到</li>
<li><strong>返回值是Promise</strong>：<code>async/await</code>的返回值是一个Promise，我们这里也需要保持一致，给返回值包一个Promise</li>
</ol>
<p>我们改造一下run方法：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">run</span>(<span class="params">gen</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 把返回值包装成promise</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">var</span> g = gen()</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">function</span> <span class="title">_next</span>(<span class="params">val</span>) </span>&#123;</span><br><span class="line">            <span class="comment">// 错误处理</span></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">var</span> res = g.next(val) </span><br><span class="line">                &#125; <span class="keyword">catch</span>(err) &#123;</span><br><span class="line">                    <span class="keyword">return</span> reject(err); </span><br><span class="line">                &#125;</span><br><span class="line">            <span class="keyword">if</span>(res.done) &#123;</span><br><span class="line">                <span class="keyword">return</span> resolve(res.value);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// res.value包装为promise，以兼容yield后面跟基本类型的情况</span></span><br><span class="line">            <span class="built_in">Promise</span>.resolve(res.value).then(</span><br><span class="line">                val =&gt; &#123;</span><br><span class="line">                    _next(val);</span><br><span class="line">                &#125;, </span><br><span class="line">                err =&gt; &#123;</span><br><span class="line">                    <span class="comment">// 抛出错误</span></span><br><span class="line">                    g.throw(err)</span><br><span class="line">                &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">        _next();</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后我们可以测试一下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span>* <span class="title">myGenerator</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="keyword">yield</span> <span class="built_in">Promise</span>.resolve(<span class="number">1</span>)) </span><br><span class="line">        <span class="built_in">console</span>.log(<span class="keyword">yield</span> <span class="number">2</span>)   <span class="comment">// 2</span></span><br><span class="line">        <span class="built_in">console</span>.log(<span class="keyword">yield</span> <span class="built_in">Promise</span>.reject(<span class="string">&#x27;error&#x27;</span>))</span><br><span class="line">    &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(error)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> result = run(myGenerator)     <span class="comment">// result是一个Promise</span></span><br><span class="line"><span class="comment">// 输出 1 2 error</span></span><br></pre></td></tr></table></figure>

<p>到这里，一个<code>async/await</code>的实现基本完成了。最后我们可以看一下babel对async/await的转换结果，其实整体的思路是一样的，但是写法稍有不同：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 相当于我们的run()</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">_asyncToGenerator</span>(<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// return一个function，和async保持一致。我们的run直接执行了Generator，其实是不太规范的</span></span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> self = <span class="built_in">this</span></span><br><span class="line">        <span class="keyword">var</span> args = <span class="built_in">arguments</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function"><span class="keyword">function</span>(<span class="params">resolve, reject</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">var</span> gen = fn.apply(self, args);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 相当于我们的_next()</span></span><br><span class="line">            <span class="function"><span class="keyword">function</span> <span class="title">_next</span>(<span class="params">value</span>) </span>&#123;</span><br><span class="line">                asyncGeneratorStep(gen, resolve, reject, _next, _throw, <span class="string">&#x27;next&#x27;</span>, value);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 处理异常</span></span><br><span class="line">            <span class="function"><span class="keyword">function</span> <span class="title">_throw</span>(<span class="params">err</span>) </span>&#123;</span><br><span class="line">                asyncGeneratorStep(gen, resolve, reject, _next, _throw, <span class="string">&#x27;throw&#x27;</span>, err);</span><br><span class="line">            &#125;</span><br><span class="line">            _next(<span class="literal">undefined</span>);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">asyncGeneratorStep</span>(<span class="params">gen, resolve, reject, _next, _throw, key, arg</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">var</span> info = gen[key](arg);</span><br><span class="line">        <span class="keyword">var</span> value = info.value;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">        reject(error);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (info.done) &#123;</span><br><span class="line">        resolve(value);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="built_in">Promise</span>.resolve(value).then(_next, _throw);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>使用方式：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> foo = _asyncToGenerator(<span class="function"><span class="keyword">function</span>* (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="keyword">yield</span> <span class="built_in">Promise</span>.resolve(<span class="number">1</span>))   <span class="comment">// 1</span></span><br><span class="line">        <span class="built_in">console</span>.log(<span class="keyword">yield</span> <span class="number">2</span>)                    <span class="comment">// 2</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;3&#x27;</span></span><br><span class="line">    &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">    	<span class="built_in">console</span>.log(error)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">foo().then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(res)                          <span class="comment">// 3</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>有关<code>async/await</code>的实现，到这里就告一段落了。但是直到结尾，我们也不知道await到底是如何暂停执行的，有关await暂停执行的秘密，我们还要到Generator的实现中去寻找答案</p>
<h1 id="Generator实现"><a href="#Generator实现" class="headerlink" title="Generator实现"></a>Generator实现</h1><p>我们从一个简单的Generator使用实例开始，一步步探究Generator的实现原理：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span>* <span class="title">foo</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;result1&#x27;</span></span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;result2&#x27;</span></span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;result3&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line">  </span><br><span class="line"><span class="keyword">const</span> gen = foo()</span><br><span class="line"><span class="built_in">console</span>.log(gen.next().value)</span><br><span class="line"><span class="built_in">console</span>.log(gen.next().value)</span><br><span class="line"><span class="built_in">console</span>.log(gen.next().value)</span><br></pre></td></tr></table></figure>

<p>我们可以在<a target="_blank" rel="noopener" href="https://babeljs.io/repl/#?browsers=&build=&builtIns=false&spec=false&loose=false&code_lz=GYVwdgxgLglg9mAVAAmHOAKAlMg3gKGWQE8YBTAGwBNkByAJzIGcQKoBGWwk86uxlmwBMXIqUo0GzVlADMXAL7d8EBEyjIA5mTDIAvKnTYVauBTIA6CnE0ZtYC2DIAPKNgsA3AIYUQZLCZgTGaW1rb2ji5uWJ4-fgGqQSFWNnY6ka7u3r7-QA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=es2015%2Creact%2Cstage-2&prettier=false&targets=&version=7.5.5&externalPlugins=">babel官网</a>上在线转化这段代码，看看ES5环境下是如何实现Generator的：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&quot;use strict&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> _marked =</span><br><span class="line"><span class="comment">/*#__PURE__*/</span></span><br><span class="line">regeneratorRuntime.mark(foo);</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> regeneratorRuntime.wrap(<span class="function"><span class="keyword">function</span> <span class="title">foo$</span>(<span class="params">_context</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">while</span> (<span class="number">1</span>) &#123;</span><br><span class="line">            <span class="keyword">switch</span> (_context.prev = _context.next) &#123;</span><br><span class="line">                <span class="keyword">case</span> <span class="number">0</span>:</span><br><span class="line">                    _context.next = <span class="number">2</span>;</span><br><span class="line">                    <span class="keyword">return</span> <span class="string">&#x27;result1&#x27;</span>;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">                    _context.next = <span class="number">4</span>;</span><br><span class="line">                    <span class="keyword">return</span> <span class="string">&#x27;result2&#x27;</span>;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">case</span> <span class="number">4</span>:</span><br><span class="line">                    _context.next = <span class="number">6</span>;</span><br><span class="line">                    <span class="keyword">return</span> <span class="string">&#x27;result3&#x27;</span>;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">case</span> <span class="number">6</span>:</span><br><span class="line">                <span class="keyword">case</span> <span class="string">&quot;end&quot;</span>:</span><br><span class="line">                    <span class="keyword">return</span> _context.stop();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, _marked);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> gen = foo();</span><br><span class="line"><span class="built_in">console</span>.log(gen.next().value);</span><br><span class="line"><span class="built_in">console</span>.log(gen.next().value);</span><br><span class="line"><span class="built_in">console</span>.log(gen.next().value);</span><br></pre></td></tr></table></figure>

<p>代码咋一看不长，但如果仔细观察会发现有两个不认识的东西 —— <code>regeneratorRuntime.mark</code>和<code>regeneratorRuntime.wrap</code>，这两者其实是 regenerator-runtime 模块里的两个方法，regenerator-runtime 模块来自facebook的 regenerator 模块，完整代码在<a target="_blank" rel="noopener" href="https://github.com/facebook/regenerator/blob/master/packages/regenerator-runtime/runtime.js">runtime.js</a>，这个runtime有700多行…-_-||，因此我们不能全讲，不太重要的部分我们就简单地过一下，重点讲解暂停执行相关部分代码</p>
<blockquote>
<p>个人觉得啃源码的效果不是很好，建议读者拉到末尾先看结论和简略版实现，源码作为一个补充理解</p>
</blockquote>
<h2 id="regeneratorRuntime-mark"><a href="#regeneratorRuntime-mark" class="headerlink" title="regeneratorRuntime.mark()"></a>regeneratorRuntime.mark()</h2><p><code>regeneratorRuntime.mark(foo)</code>这个方法在第一行被调用，我们先看一下runtime里mark()方法的定义</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// runtime.js里的定义稍有不同，多了一些判断，以下是编译后的代码</span></span><br><span class="line">runtime.mark = <span class="function"><span class="keyword">function</span>(<span class="params">genFun</span>) </span>&#123;</span><br><span class="line">    genFun.__proto__ = GeneratorFunctionPrototype;</span><br><span class="line">    genFun.prototype = <span class="built_in">Object</span>.create(Gp);</span><br><span class="line">    <span class="keyword">return</span> genFun;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>这里边<code>GeneratorFunctionPrototype</code>和<code>Gp</code>我们都不认识，他们被定义在runtime里，不过没关系，我们只要知道<code>mark()方法</code>为生成器函数（foo）绑定了一系列原型就可以了，这里就简单地过了</p>
<h2 id="regeneratorRuntime-wrap"><a href="#regeneratorRuntime-wrap" class="headerlink" title="regeneratorRuntime.wrap()"></a>regeneratorRuntime.wrap()</h2><p>从上面babel转化的代码我们能看到，执行<code>foo()</code>，其实就是执行<code>wrap()</code>，那么这个方法起到什么作用呢，他想包装一个什么东西呢，我们先来看看wrap方法的定义：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//runtime.js里的定义稍有不同，多了一些判断，以下是编译后的代码</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">wrap</span>(<span class="params">innerFn, outerFn, self</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> generator = <span class="built_in">Object</span>.create(outerFn.prototype);</span><br><span class="line">    <span class="keyword">var</span> context = <span class="keyword">new</span> Context([]);</span><br><span class="line">    generator._invoke = makeInvokeMethod(innerFn, self, context);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> generator;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>wrap方法先是创建了一个generator，并继承<code>outerFn.prototype</code>；然后new了一个<code>context对象</code>；<code>makeInvokeMethod方法</code>接收<code>innerFn(对应foo$)</code>、<code>context</code>和<code>this</code>，并把返回值挂到<code>generator._invoke</code>上；最后return了generator。<strong>其实wrap()相当于是给generator增加了一个_invoke方法</strong></p>
<p>这段代码肯定让人产生很多疑问，outerFn.prototype是什么，Context又是什么，makeInvokeMethod又做了哪些操作。下面我们就来一一解答：</p>
<blockquote>
<p><code>outerFn.prototype</code>其实就是<code>genFun.prototype</code>，</p>
</blockquote>
<p>这个我们结合一下上面的代码就能知道</p>
<blockquote>
<p><code>context</code>可以直接理解为这样一个全局对象，用于储存各种状态和上下文：</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> ContinueSentinel = &#123;&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> context = &#123;</span><br><span class="line">    done: <span class="literal">false</span>,</span><br><span class="line">    method: <span class="string">&quot;next&quot;</span>,</span><br><span class="line">    next: <span class="number">0</span>,</span><br><span class="line">    prev: <span class="number">0</span>,</span><br><span class="line">    abrupt: <span class="function"><span class="keyword">function</span>(<span class="params">type, arg</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> record = &#123;&#125;;</span><br><span class="line">        record.type = type;</span><br><span class="line">        record.arg = arg;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.complete(record);</span><br><span class="line">    &#125;,</span><br><span class="line">    complete: <span class="function"><span class="keyword">function</span>(<span class="params">record, afterLoc</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (record.type === <span class="string">&quot;return&quot;</span>) &#123;</span><br><span class="line">            <span class="built_in">this</span>.rval = <span class="built_in">this</span>.arg = record.arg;</span><br><span class="line">            <span class="built_in">this</span>.method = <span class="string">&quot;return&quot;</span>;</span><br><span class="line">            <span class="built_in">this</span>.next = <span class="string">&quot;end&quot;</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> ContinueSentinel;</span><br><span class="line">    &#125;,</span><br><span class="line">    stop: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">this</span>.done = <span class="literal">true</span>;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.rval;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>makeInvokeMethod<code>的定义如下，它return了一个</code>invoke方法<code>，invoke用于判断当前状态和执行下一步，其实就是我们调用的</code>next()</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 以下是编译后的代码</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">makeInvokeMethod</span>(<span class="params">innerFn, context</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 将状态置为start</span></span><br><span class="line">    <span class="keyword">var</span> state = <span class="string">&quot;start&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">invoke</span>(<span class="params">method, arg</span>) </span>&#123;</span><br><span class="line">        <span class="comment">// 已完成</span></span><br><span class="line">        <span class="keyword">if</span> (state === <span class="string">&quot;completed&quot;</span>) &#123;</span><br><span class="line">        	<span class="keyword">return</span> &#123; <span class="attr">value</span>: <span class="literal">undefined</span>, <span class="attr">done</span>: <span class="literal">true</span> &#125;;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        context.method = method;</span><br><span class="line">        context.arg = arg;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 执行中</span></span><br><span class="line">        <span class="keyword">while</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">            state = <span class="string">&quot;executing&quot;</span>;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">var</span> record = &#123;</span><br><span class="line">                type: <span class="string">&quot;normal&quot;</span>,</span><br><span class="line">                arg: innerFn.call(self, context)    <span class="comment">// 执行下一步,并获取状态(其实就是switch里边return的值)</span></span><br><span class="line">            &#125;;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (record.type === <span class="string">&quot;normal&quot;</span>) &#123;</span><br><span class="line">                <span class="comment">// 判断是否已经执行完成</span></span><br><span class="line">                state = context.done ? <span class="string">&quot;completed&quot;</span> : <span class="string">&quot;yield&quot;</span>;</span><br><span class="line"></span><br><span class="line">                <span class="comment">// ContinueSentinel其实是一个空对象,record.arg === &#123;&#125;则跳过return进入下一个循环</span></span><br><span class="line">                <span class="comment">// 什么时候record.arg会为空对象呢, 答案是没有后续yield语句或已经return的时候,也就是switch返回了空值的情况(跟着上面的switch走一下就知道了)</span></span><br><span class="line">                <span class="keyword">if</span> (record.arg === ContinueSentinel) &#123;</span><br><span class="line">                    <span class="keyword">continue</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="comment">// next()的返回值</span></span><br><span class="line">                <span class="keyword">return</span> &#123;</span><br><span class="line">                    value: record.arg,</span><br><span class="line">                    done: context.done</span><br><span class="line">                &#125;;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>为什么<code>generator._invoke</code>实际上就是<code>gen.next</code>呢，因为在runtime对于next()的定义中，next()其实就return了_invoke方法</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Helper for defining the .next, .throw, and .return methods of the</span></span><br><span class="line"><span class="comment">// Iterator interface in terms of a single ._invoke method.</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">defineIteratorMethods</span>(<span class="params">prototype</span>) </span>&#123;</span><br><span class="line">    [<span class="string">&quot;next&quot;</span>, <span class="string">&quot;throw&quot;</span>, <span class="string">&quot;return&quot;</span>].forEach(<span class="function"><span class="keyword">function</span>(<span class="params">method</span>) </span>&#123;</span><br><span class="line">        prototype[method] = <span class="function"><span class="keyword">function</span>(<span class="params">arg</span>) </span>&#123;</span><br><span class="line">        	<span class="keyword">return</span> <span class="built_in">this</span>._invoke(method, arg);</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">defineIteratorMethods(Gp);</span><br></pre></td></tr></table></figure>



<h2 id="低配实现-amp-调用流程分析"><a href="#低配实现-amp-调用流程分析" class="headerlink" title="低配实现 &amp; 调用流程分析"></a>低配实现 &amp; 调用流程分析</h2><p>这么一遍源码下来，估计很多读者还是懵逼的，毕竟源码中纠集了很多概念和封装，一时半会不好完全理解，让我们跳出源码，实现一个简单的Generator，然后再回过头看源码，会得到更清晰的认识</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 生成器函数根据yield语句将代码分割为switch-case块，后续通过切换_context.prev和_context.next来分别执行各个case</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">gen$</span>(<span class="params">_context</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">while</span> (<span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">switch</span> (_context.prev = _context.next) &#123;</span><br><span class="line">            <span class="keyword">case</span> <span class="number">0</span>:</span><br><span class="line">                _context.next = <span class="number">2</span>;</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&#x27;result1&#x27;</span>;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">                _context.next = <span class="number">4</span>;</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&#x27;result2&#x27;</span>;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">case</span> <span class="number">4</span>:</span><br><span class="line">                _context.next = <span class="number">6</span>;</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&#x27;result3&#x27;</span>;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">case</span> <span class="number">6</span>:</span><br><span class="line">                <span class="keyword">case</span> <span class="string">&quot;end&quot;</span>:</span><br><span class="line">                <span class="keyword">return</span> _context.stop();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 低配版context  </span></span><br><span class="line"><span class="keyword">var</span> context = &#123;</span><br><span class="line">    next:<span class="number">0</span>,</span><br><span class="line">    prev: <span class="number">0</span>,</span><br><span class="line">    done: <span class="literal">false</span>,</span><br><span class="line">    stop: <span class="function"><span class="keyword">function</span> <span class="title">stop</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    	<span class="built_in">this</span>.done = <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 低配版invoke</span></span><br><span class="line"><span class="keyword">let</span> gen = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        next: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">            value = context.done ? <span class="literal">undefined</span>: gen$(context)</span><br><span class="line">            done = context.done</span><br><span class="line">            <span class="keyword">return</span> &#123;</span><br><span class="line">                value,</span><br><span class="line">                done</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125; </span><br><span class="line"></span><br><span class="line"><span class="comment">// 测试使用</span></span><br><span class="line"><span class="keyword">var</span> g = gen() </span><br><span class="line">g.next()  <span class="comment">// &#123;value: &quot;result1&quot;, done: false&#125;</span></span><br><span class="line">g.next()  <span class="comment">// &#123;value: &quot;result2&quot;, done: false&#125;</span></span><br><span class="line">g.next()  <span class="comment">// &#123;value: &quot;result3&quot;, done: false&#125;</span></span><br><span class="line">g.next()  <span class="comment">// &#123;value: undefined, done: true&#125;</span></span><br></pre></td></tr></table></figure>

<p>这段代码并不难理解，我们分析一下调用流程：</p>
<ol>
<li>我们定义的<code>function*</code>生成器函数被转化为以上代码</li>
<li>转化后的代码分为三大块：<ul>
<li><code>gen$(_context)</code>由yield分割生成器函数代码而来</li>
<li><code>context对象</code>用于储存函数执行上下文</li>
<li><code>invoke()方法</code>定义next()，用于执行gen$(_context)来跳到下一步</li>
</ul>
</li>
<li>当我们调用<code>g.next()</code>，就相当于调用<code>invoke()方法</code>，执行<code>gen$(_context)</code>，进入switch语句，switch根据context的标识，执行对应的case块，return对应结果</li>
<li>当生成器函数运行到末尾（没有下一个yield或已经return），switch匹配不到对应代码块，就会return空值，这时<code>g.next()</code>返回<code>&#123;value: undefined, done: true&#125;</code></li>
</ol>
<p>从中我们可以看出，<strong>Generator实现的核心在于<code>上下文的保存</code>，函数并没有真的被挂起，每一次yield，其实都执行了一遍传入的生成器函数，只是在这个过程中间用了一个context对象储存上下文，使得每次执行生成器函数的时候，都可以从上一个执行结果开始执行，看起来就像函数被挂起了一样</strong></p>
<h1 id="总结-amp-致谢"><a href="#总结-amp-致谢" class="headerlink" title="总结 &amp; 致谢"></a>总结 &amp; 致谢</h1><p>有关Promise、async/await、Generator的原理就实现到这里了，感谢大家能够跟我一起走完全程，不知不觉，我们花了近9千字来讲述有关异步编程的故事，异步编程的世界环环相扣，一开始，笔者只是出于对await挂起机制的好奇，后来，从一个 “await是如何实现暂停执行” 的小问题，引出了对异步编程的一系列思考和实现原理。三者的实现，其实也是前端异步编程一步步演化推进的过程。</p>
<p>成文过程中得到很多大佬的帮助，这四篇参考文章都是我阅读了很多相关文章后精选的四篇，建议大家结合阅读，大佬们写的比我好很多，另外感谢冴羽大佬在Generator机制上给予的解惑~</p>
<blockquote>
<p>前端技匠：<a target="_blank" rel="noopener" href="https://juejin.im/post/6844903989083897870">各种源码实现，你想要的这里都有</a><br> 神三元：<a target="_blank" rel="noopener" href="https://juejin.im/post/6844903702457925640">我如何实现Promise</a><br> winty：<a target="_blank" rel="noopener" href="https://juejin.im/post/6844903988584775693#heading-0">async/await 原理及执行顺序分析</a><br> 冴羽：<a target="_blank" rel="noopener" href="https://juejin.im/post/6844903701908291592">ES6 系列之 Babel 将 Generator   编译成了什么样子</a></p>
</blockquote>

    </div>

    
    
    
      
<div>
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
</div>
        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Promise/" rel="tag"><i class="fa fa-tag"></i> Promise</a>
              <a href="/tags/async/" rel="tag"><i class="fa fa-tag"></i> async</a>
              <a href="/tags/Generator/" rel="tag"><i class="fa fa-tag"></i> Generator</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/10/25/hexo%E5%8D%9A%E5%AE%A2/" rel="prev" title="hexo搭建博客">
      <i class="fa fa-chevron-left"></i> hexo搭建博客
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/02/10/js%E5%87%BD%E6%95%B0%E6%89%8B%E5%86%99/" rel="next" title="js函数手写">
      js函数手写 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Promise%E5%AE%9E%E7%8E%B0"><span class="nav-text">Promise实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E8%A7%82%E5%AF%9F%E8%80%85%E6%A8%A1%E5%BC%8F"><span class="nav-text">1. 观察者模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-Promise-A-%E8%A7%84%E8%8C%83"><span class="nav-text">2. Promise A+规范</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-then%E7%9A%84%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8"><span class="nav-text">3. then的链式调用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E5%80%BC%E7%A9%BF%E9%80%8F-amp-%E7%8A%B6%E6%80%81%E5%B7%B2%E5%8F%98%E6%9B%B4%E7%9A%84%E6%83%85%E5%86%B5"><span class="nav-text">4.值穿透 &amp; 状态已变更的情况</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-%E5%85%BC%E5%AE%B9%E5%90%8C%E6%AD%A5%E4%BB%BB%E5%8A%A1"><span class="nav-text">5.兼容同步任务</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Promise-prototype-catch"><span class="nav-text">Promise.prototype.catch()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Promise-prototype-finally"><span class="nav-text">Promise.prototype.finally()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Promise-resolve"><span class="nav-text">Promise.resolve()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Promise-reject"><span class="nav-text">Promise.reject()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Promise-all"><span class="nav-text">Promise.all()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Promise-race"><span class="nav-text">Promise.race()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%8C%E6%95%B4%E4%BB%A3%E7%A0%81"><span class="nav-text">完整代码</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#async-await%E5%AE%9E%E7%8E%B0"><span class="nav-text">async&#x2F;await实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E8%87%AA%E5%8A%A8%E6%89%A7%E8%A1%8C"><span class="nav-text">1.自动执行</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E8%BF%94%E5%9B%9EPromise-amp-%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86"><span class="nav-text">2.返回Promise &amp; 异常处理</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Generator%E5%AE%9E%E7%8E%B0"><span class="nav-text">Generator实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#regeneratorRuntime-mark"><span class="nav-text">regeneratorRuntime.mark()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#regeneratorRuntime-wrap"><span class="nav-text">regeneratorRuntime.wrap()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%8E%E9%85%8D%E5%AE%9E%E7%8E%B0-amp-%E8%B0%83%E7%94%A8%E6%B5%81%E7%A8%8B%E5%88%86%E6%9E%90"><span class="nav-text">低配实现 &amp; 调用流程分析</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%80%BB%E7%BB%93-amp-%E8%87%B4%E8%B0%A2"><span class="nav-text">总结 &amp; 致谢</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="hxy"
      src="/images/Robben.gif">
  <p class="site-author-name" itemprop="name">hxy</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">80</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">120</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/huxingyi1997" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;huxingyi1997" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:huxingyi1997@zju.edu.cn" title="E-Mail → mailto:huxingyi1997@zju.edu.cn" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-frog"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">hxy</span>
</div>

<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共1039.2k字</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : true,
      appId      : 'pQsO3ySbU4VtWN2j1FLA74Ha-gzGzoHsz',
      appKey     : 'QYacMDY2VY7Wazprg1X6FiUv',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

  
  <!-- 动态背景特效 -->
  <!-- 樱花特效 -->
    <script async src="/js/src/sakura.js"></script>
    <script async src="/js/src/fairyDustCursor.js"></script>
</body>
</html>
